package com.cssy.yd.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicSkDAO;
import com.cssy.yd.logic.dao.LogicSkItemDAO;
import com.cssy.yd.logic.dao.LogicSoWareDAO;
import com.cssy.yd.logic.entity.LogicSoWareDO;
import com.cssy.yd.logic.entity.LogicSkDO;
import com.cssy.yd.logic.entity.LogicSkItemDO;
import com.cssy.yd.logic.service.ILogicSkService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicSkService")
public class LogicSkServiceImpl implements ILogicSkService {
	@Resource(name = "logicSkDAO")
	private LogicSkDAO logicSkDAO;

	@Resource(name = "logicSkItemDAO")
	private LogicSkItemDAO logicSkItemDAO;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicSoWareDAO")
	private LogicSoWareDAO logicSoWareDAO;
	
	

	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicSkDO> list = logicSkDAO.find(scs);
		rs.setRecordCount(logicSkDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i = logicSkDAO.deleteLogicSkDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer update(LogicSkDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicSkDAO.updateLogicSkDO(t);
	}

	@Override
	public LogicSkDO save(LogicSkDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		t.setId(IDCodeTypeUtil.getId());
		logicSkDAO.insertLogicSkDO(t);
		return t;
	}

	@Override
	public LogicSkDO findListById(String id) throws SyBaseException {
		return logicSkDAO.findLogicSkDOByPrimaryKey(id);
	}

	@Override
	public SearchResult findItemListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicSkItemDO> list = logicSkItemDAO.find(scs);
		rs.setRecordCount(logicSkItemDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer deleteItem(String id) throws SyBaseException {
		Integer i = logicSkItemDAO.deleteLogicSkItemDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer updateItem(LogicSkItemDO t) throws SyBaseException {
		return logicSkItemDAO.updateLogicSkItemDO(t);
	}

	@Override
	public LogicSkItemDO saveItem(LogicSkItemDO t) throws SyBaseException {
		t.setId(IDCodeTypeUtil.getId());
		logicSkItemDAO.insertLogicSkItemDO(t);
		return t;
	}

	@Override
	public List<LogicSkItemDO> findItemListBysoid(String soid)
			throws SyBaseException {

		return logicSkItemDAO.finditembysoid(soid);
	}

	@Override
	public Double findLastedDOByExample(SearchConditions scs)
			throws SyBaseException {
		return logicSkDAO.findLastedDOByOricode(scs);
	}

	@Override
	public LogicSkItemDO findItemListById(String id) throws SyBaseException {
		return logicSkItemDAO.findLogicSkItemDOByPrimaryKey(id);
	}

	@Override
	public void sksave(HttpServletRequest request, LogicSkDO curAP)
			throws SyBaseException, SyCodeException {
		try {//新增草稿
			String yfDate = request.getParameter("yfDate");
			String itemdata = request.getParameter("itemdata");	
 			List<LogicSkItemDO> itemlist = JSONArray.parseArray(itemdata, LogicSkItemDO.class);	
 			// 检查是否已有此销售出库单的收款单草稿
			String oricode = request.getParameter("oriCode");
			SearchConditions scs = new SearchConditions();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus", "0", SearchCondition.OP_EQUAL);
			int skcount = logicSkDAO.count(scs);
			if(skcount > 0){
				throw new SyBaseException("已有此销售出库的收款单草稿，请先处理已有的单据");
			}		
			 
				String id = IDCodeTypeUtil.getId();
				curAP.setId(id);
				curAP.setSkCode(syCodeService.getCode("SK","SK",SyCode.DATE_YYMM,5));
				String skcode = curAP.getSkCode();
				curAP.setBillStatus(Integer.parseInt("0"));
				curAP.setSkState(Integer.parseInt("0"));
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				if (yfDate != null && !"".equals(yfDate)) {
					curAP.setYfDate(DateUtils.stringToDate(yfDate));
				}	
				logicSkDAO.insertLogicSkDO(curAP);
				for (int i = 0; i < itemlist.size(); i++) {
					itemlist.get(i).setId(IDCodeTypeUtil.getId());
					itemlist.get(i).setSoid(id);
					itemlist.get(i).setSkcode(skcode);
					logicSkItemDAO.insertLogicSkItemDO(itemlist.get(i));
				}
 			
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}
	
	@Override
	public void skcommit(HttpServletRequest request, LogicSkDO curAP)
			throws SyBaseException, SyCodeException {
		try {
			String yfDate = request.getParameter("yfDate");
			String itemdata = request.getParameter("itemdata");	
			String itemdelete = request.getParameter("itemdelete");
			String soware_no = request.getParameter("oriCode");
 			List<LogicSkItemDO> itemlist = JSONArray.parseArray(itemdata, LogicSkItemDO.class);	
 			List<LogicSoWareDO> sowarelist = new ArrayList<LogicSoWareDO>();
 			LogicSoWareDO pd = null;
 			Double presshk = Double.parseDouble("0");  //本次实收货款
 			Double prewshk = Double.parseDouble("0"); //本次未收货款
 			if (itemdelete != null && !"".equals(itemdelete)) {
				List<LogicSkItemDO> silist = JSONArray.parseArray(itemdelete, LogicSkItemDO.class);
				for (LogicSkItemDO sido : silist) {
					if (sido.getId() != null&& !"".equals(sido.getId())) {
						logicSkItemDAO.deleteLogicSkItemDOByPrimaryKey(sido.getId());
					}
				}
			}
 			//提交收款
 			if(itemlist != null && itemlist.size() > 0){
				for (LogicSkItemDO skitem : itemlist) {
					skitem.setYshk((skitem.getYshk()==null ? 0 : skitem.getYshk()) + (skitem.getSshk()==null?0:skitem.getSshk()));
					skitem.setWshk((skitem.getWshk()==null ? 0 : skitem.getWshk()) - (skitem.getSshk()==null ? 0 : skitem.getSshk()));
					skitem.setSshk(skitem.getSshk()==null ? 0: skitem.getSshk());
					curAP.setYshk((curAP.getYshk()==null ? 0: curAP.getYshk()) + skitem.getSshk());
					presshk += skitem.getSshk();
					prewshk += skitem.getWshk();
				}
			}
			curAP.setBillStatus(2);
			SearchConditions scs = new SearchConditions();
			scs.addCondition("no", soware_no, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
			sowarelist = logicSoWareDAO.find(scs);
			if(sowarelist!=null&&sowarelist.size()>0){ //取得对应的销售出库单
				pd = sowarelist.get(0);
			}
 			SearchConditions scs1 = new SearchConditions();
			scs1.addCondition("oricode", soware_no, SearchCondition.OP_EQUAL);
			scs1.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
 			Double hisyshk = logicSkDAO.findLastedDOByOricode(scs1);//最近一次收款后收款单的已收金额
 			Double hiswshk = new Double("0.0");
 			
 			if(hisyshk == null||hisyshk==0){
 				hisyshk = Double.parseDouble("0.0");
 			}
 			hiswshk = new BigDecimal(curAP.getMoney().toString()).subtract(new BigDecimal(hisyshk.toString())).doubleValue(); //最近一次收款后的未收金额
 			if(presshk.doubleValue() < hiswshk.doubleValue()) {
 				curAP.setSkState(1);
 				if(pd.getId()!=null){
 					pd.setPaymentstatus(1);  //根据收款情况改变销售出库单中的付款状态
 				}
 			} else if(presshk.doubleValue() == hiswshk.doubleValue()){
 				curAP.setSkState(2);
 				if(pd.getId()!=null){
 					pd.setPaymentstatus(2);
 				}
 			} else if(presshk.doubleValue() > hiswshk.doubleValue()) {
 				throw new SyBaseException("您本次收款大于收款单历史未收款！");
 			}
 			
 			int j = logicSoWareDAO.updateLogicSoWareDO(pd);
			if(j < 0){
				throw new SyBaseException("提交失败");
			}
			if (yfDate != null && !"".equals(yfDate)) {
				curAP.setYfDate(DateUtils.stringToDate(yfDate));
			}				
			curAP.setDuuser(SessionUtil.getUser(request).getName());
			curAP.setDutime(new Date());
			logicSkDAO.updateLogicSkDO(curAP);
			for (int i = 0; i < itemlist.size(); i++) {
				logicSkItemDAO.updateLogicSkItemDO(itemlist.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}

}
